import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref } from 'vue'

const useLazyData = (fn) => {
  const target = ref(null)

  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        //   1.停止观察
        stop()
        // 2.发请求
        fn()
      }
    }, {
      // threshold 进入的面积,0-1 之间
      threshold: 0
    }
  )
  return target
}

export const useCountdown = () => {
  const time = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    // 每隔多长时间做什么 回调
    time.value--
    if (time.value <= 0) {
      pause()
    }
    // console.log('useIntervalFn', Date.now())
  }, 1000, { immediate: false })
  // pause: 暂停,
  // resume: 开始
  const start = (num) => {
    time.value = num
    resume()
  }

  return { time, start }
}
export default useLazyData
